package com.lujieni.springbootrocketmq.service;

import com.lujieni.springbootrocketmq.dto.OrderDTO;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MessageProducer {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    public <T> void sendMessage(String topic, String tag, T payLoad) {
        // 构建完整的destination，格式为 topic:tag
        System.out.println("prepare send time:"+new Date() + "message:"+payLoad);
        String destination = String.format("%s:%s", topic, tag);
        rocketMQTemplate.syncSend(destination, MessageBuilder.withPayload(payLoad).build());
    }

    public void sendMessageOrder(String topic, String tag, OrderDTO orderDTO) {
        // 构建完整的destination，格式为 topic:tag
        System.out.println("prepare send time:"+new Date() + "message:"+orderDTO);
        String destination = String.format("%s:%s", topic, tag);
        rocketMQTemplate.syncSendOrderly(destination, MessageBuilder.withPayload(orderDTO).build(), String.valueOf(orderDTO.getOrderId()));
    }

    public void sendMessageDelay(String topic, String tag, OrderDTO orderDTO) {
        // 构建完整的destination，格式为 topic:tag
        System.out.println("prepare send time:"+new Date() + "message:"+orderDTO);
        String destination = String.format("%s:%s", topic, tag);
        rocketMQTemplate.syncSend(destination, MessageBuilder.withPayload(orderDTO).build(), 3000, 2); //延迟5秒消费消息
    }

    public void sendMessageTransaction(String topic, String tag, OrderDTO orderDTO) {
        // 发送事务消息
        System.out.println("prepare send time:"+new Date() + "message:"+orderDTO);
        String destination = String.format("%s:%s", topic, tag);
        rocketMQTemplate.sendMessageInTransaction(destination, MessageBuilder.withPayload(orderDTO).build(), null); //延迟5秒消费消息

    }
}